package com.tms.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tms.admin.checkUtil.DataCheck;
import com.tms.admin.entity.TmsCustomer;
import com.tms.admin.entity.TmsDriver;
import com.tms.admin.entity.TmsLogistics;
import com.tms.admin.entity.enums.LogisticsGetStatusEnum;
import com.tms.admin.entity.vo.CustomerQueryVO;
import com.tms.admin.handler.TMSException;
import com.tms.admin.service.TmsCustomerService;
import com.tms.admin.mapper.TmsCustomerMapper;
import com.tms.admin.service.TmsLogisticsService;
import com.tms.common.entity.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
* @author 86132
* @description 针对表【tms_customer】的数据库操作Service实现
* @createDate 2022-09-06 21:18:21
*/
@Service
public class TmsCustomerServiceImpl extends ServiceImpl<TmsCustomerMapper, TmsCustomer>
    implements TmsCustomerService{

    @Autowired
    private TmsLogisticsService logisticsService;
    /**
     * 顾客信息分页/模糊查询
     * @param customerQueryVO
     */
    @Override
    public Map<String, Object> getPageByCondition(CustomerQueryVO customerQueryVO) {
        /**
         * Step 1. 根据 VO 类, 取出里面所有的查询条件
         *
         * Step 2. 根据查询条件来封装 Wrapper
         *
         * Step 3. 执行分页查询, 获取到 Page 对象
         *
         * Step 4. 将 Page 对象 封装到 Map
         */
        // Step 1.
        String name = customerQueryVO.getName();
        String phone = customerQueryVO.getPhone();
        if (name == null)
            name = "";
        if (phone == null)
            phone = "";
        Integer pageNum = customerQueryVO.getPageNum();
        Integer pageSize = customerQueryVO.getPageSize();
        // Step 2
        LambdaQueryWrapper<TmsCustomer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(TmsCustomer::getName,name)
                    .like(TmsCustomer::getPhone,phone);
        // Step 3
        // 创建分页对象——page,初始化分页大小和页数
        if (pageNum == null){
            pageNum = 1;
        }
        if (pageSize == null){
            pageSize = 5;
        }
        Page<TmsCustomer> customerPage = new Page<>(pageNum,pageSize);
        baseMapper.selectPage(customerPage,queryWrapper);
        // Step 4 封装分页信息
        Map<String,Object> pageInfoMap = new HashMap<>();
        pageInfoMap.put("customerList",customerPage.getRecords());
        pageInfoMap.put("pageNum",customerPage.getCurrent());
        pageInfoMap.put("pageSize",customerPage.getSize());
        pageInfoMap.put("total",customerPage.getTotal());
        pageInfoMap.put("hasNext",customerPage.hasNext());
        pageInfoMap.put("hasPrevious",customerPage.hasPrevious());
        return pageInfoMap;
    }

    /**
     * 新增顾客信息
     * @param customer
     */
    @Override
    public void addCustomer(TmsCustomer customer) {
        /**
         * Step 1. 获取顾客的属性, name, phone, addr, gender
         *
         * Step 2. 判断 name, phone, addr, gender 是否为空, 若为空则抛出异常1
         *
         * Step 3. 检查 phone 是否符合11位数字的规范, 不符合则抛出异常2
         *
         * Step 4. 最后将 customer 保存到数据库表 tms_customer 中
         */
        // Step 1
        // Step 2
        if (DataCheck.isNullToCustomer(customer)){
            throw new TMSException(ResultCode.ERROR,"客户信息不完整");
        }
        // Step 3
        if (DataCheck.isErrorToPhone(customer.getPhone())){
            throw new TMSException(ResultCode.ERROR,"电话号码格式错误");
        }
        // Step 4
        baseMapper.insert(customer);
    }

    /**
     * 删除顾客
     * @param customerIds
     */
    @Override
    public void removeCustomersById(List<Integer> customerIds) {
        /**
         * Step 1. 判断 入参 customerIds 是否为空, 为空则直接返回 ture
         *
         * Step 2. 循环遍历 customerIds, 检查该id对应的司机是否涉及级联删除，做出相应的判断
         *
         */
        // Step 1
        if (customerIds == null || customerIds.isEmpty()) {
            throw new TMSException(ResultCode.FAIL, "无可删除的顾客记录");
        }
        // Step 2
        for (Integer cId : customerIds) {
            // 判断物流表里该客户是否有未完成的收寄件，如果有，则不能删除
            LambdaQueryWrapper<TmsLogistics> logisticWrapper = new LambdaQueryWrapper();
            logisticWrapper.or().eq(TmsLogistics::getCustomerIdFrom,cId)
                           .or().eq(TmsLogistics::getCustomerIdTo,cId);
            List<TmsLogistics> logisticsList = logisticsService.getBaseMapper().selectList(logisticWrapper);
            if (!logisticsList.isEmpty()) {
                for (TmsLogistics logistic : logisticsList) {
                    if (LogisticsGetStatusEnum.NO.name().equals(logistic.getGetStatus())) {
                        throw new TMSException(ResultCode.ERROR, "该顾客还有未完成的物流，不能删除");
                    }
                }
            }
            // 如果该顾客的物流订单已经全部完成，则同时将物流表中涉及该顾客的物流信息全部删除
            logisticsService.getBaseMapper().delete(logisticWrapper);
            baseMapper.deleteById(cId);

        }
    }

    /**
     * 修改顾客信息
     * @param customer
     */
    @Override
    public void modifyCustomerById(TmsCustomer customer) {
        /**
         * Step 1. 根据 customer的 id 判断该用户是否存在，若不存在则抛出异常
         *
         * Step 2. 根据 customer 获取 name, gender, addr, phone
         *
         * Step 3. 若 phone 非空，则校验是否符合11位数字，不符合则抛出异常2
         *
         * Step 4. 调用 DAO层方法, 根据 customer 的 id 修改非空的信息
         */
        // Step 1 检验用户是否存在
        Integer cID = customer.getId();
        if (cID == null || baseMapper.selectById(cID) == null){
            throw new TMSException(ResultCode.ERROR,"不存在此顾客，无法修改");
        }
        // Step 2 数据空值检验
        if (DataCheck.isNullToCustomer(customer)){
            throw new TMSException(ResultCode.ERROR,"不允许存在空值");
        }
        // Step 3 号码格式检验
        if (DataCheck.isErrorToPhone(customer.getPhone())){
            throw new TMSException(ResultCode.ERROR,"号码格式不正确");
        }
        // Step 4
        baseMapper.updateById(customer);

    }
}




